# code:utf8
import json
import logging
import math
from datetime import datetime
from pyquery import PyQuery

from zc_core.model.items import OrderItem, Sku, ItemGroup, Catalog
from zc_core.util.batch_gen import time_to_batch_no
from zc_core.util.common import parse_time
from zc_core.util.encrypt_util import double_base64_encode, base64_decode, short_uuid, md5
from esgcc_sub.items import EsgccItemData, EsgccCompareGroup
from esgcc_sub.matcher import *

logger = logging.getLogger('rule')


# 解析catalog列表
def parse_catalog(response):
    cats = list()
    jpy = PyQuery(response.text)
    rows = jpy('dd.one_two > ul > li')
    for nav1_row in rows.items():
        # 一级分类
        nav_link = nav1_row('div.one_class_title a')
        cat1_id = match_cat_id(nav_link.attr('href'))
        cat1_name = nav_link.text().strip()
        cat1 = _build_catalog(cat1_id, cat1_name, '', 1)
        cats.append(cat1)
        # 二级分类
        nav2_rows = nav1_row('div.one_class_con dl')
        for nav2_row in nav2_rows.items():
            cat2_name = nav2_row('dt').text().strip()
            cat2_id = double_base64_encode(cat2_name)
            cat2 = _build_catalog(cat2_id, cat2_name, cat1_id, 2)
            cats.append(cat2)

            # 三级分类
            nav3_rows = nav2_row('dd a')
            for nav3_row in nav3_rows.items():
                cat3_id = match_cat_id(nav3_row.attr('href'))
                cat3_name = nav3_row.text().strip()
                cat3 = _build_catalog(cat3_id, cat3_name, cat2_id, 3)
                cats.append(cat3)

    return cats


def _build_catalog(cat_id, cat_name, parent_id, level):
    cat = Catalog()
    cat['catalogId'] = cat_id
    cat['catalogName'] = cat_name
    cat['parentId'] = parent_id
    cat['level'] = level
    if level == 3:
        cat['leafFlag'] = 1
    else:
        cat['leafFlag'] = 0
    cat['linkable'] = 0

    return cat


# 解析sku列表
def parse_sku_page(response):
    jpy = PyQuery(response.text)
    total = jpy('span.tit3').text().strip()
    cnt = match_total_goods(total)
    if cnt:
        return math.ceil(cnt / 20)

    return 0


# 解析sku列表
def parse_sku(response):
    meta = response.meta
    cat_id = meta.get('catId')

    jpy = PyQuery(response.text)

    sku_list = list()
    rows = jpy('ul.product_list li.product_item')
    for row in rows.items():
        sku_id = base64_decode(row('input.item_id').attr('value'))
        price = row('input.item_price').attr('value')
        sold_count = row('input.fl').attr('value')
        sku = Sku()
        sku['skuId'] = sku_id
        sku['salePrice'] = price
        sku['catalog3Id'] = cat_id
        sku['soldCount'] = sold_count
        sku_list.append(sku)

    return sku_list


# 解析sku列表
def parse_sku_by_group(response):
    sku_list = list()

    meta = response.meta
    same_sku_id = meta.get('skuId')
    sku = Sku()
    sku['skuId'] = same_sku_id
    sku['spuId'] = same_sku_id
    sku_list.append(sku)

    jpy = PyQuery(response.text)
    rows = jpy('table.Survey_table tr td a')
    for row in rows.items():
        sku_id = match_sku_id(row.attr('href'))
        sku = Sku()
        sku['skuId'] = sku_id
        sku['spuId'] = same_sku_id
        sku_list.append(sku)

    return sku_list


# 解析ItemData
def parse_item_data(response):
    meta = response.meta
    batch_no = meta.get('batchNo')
    sku_id = meta.get('skuId')
    spu_id = meta.get('spuId')

    jpy = PyQuery(response.text)
    supplier = jpy('div.product_top_r li.shop_name p')
    images = jpy('div#preview img#skuImg')
    nav = jpy('div.graybar_wrap div.graybar a')
    price_box = jpy('div.price_box dl')
    external_price_links = jpy('div.external_price_box ul li a')

    # -------------------------------------------------
    result = EsgccItemData()
    result['batchNo'] = batch_no
    result['skuId'] = sku_id
    result['spuId'] = spu_id
    material_code = jpy('input#materialId')
    if material_code and material_code.attr('value'):
        result['materialCode'] = material_code.attr('value').strip()
    sku_name = jpy('input#prodName_name')
    if sku_name:
        result['skuName'] = jpy('input#prodName_name').attr('value').strip()
    else:
        result['skuName'] = jpy('h1#prodName').text().strip()
    if images:
        result['skuImg'] = images.attr('src').strip()
    # 一级分类
    cat1Name = nav.eq(0).text().strip()
    result['catalog1Name'] = cat1Name
    result['catalog1Id'] = double_base64_encode(cat1Name + ':1')
    # 二级分类
    cat2Name = nav.eq(1).text().strip()
    result['catalog2Name'] = cat2Name
    result['catalog2Id'] = double_base64_encode(cat2Name + ':2')
    # 三级分类
    cat3Name = nav.eq(2).text().strip()
    result['catalog3Id'] = double_base64_encode(cat3Name)
    result['catalog3Name'] = cat3Name
    result['salePrice'] = parse_number(jpy('input#prodPrice').attr("value"))
    org_price = parse_number(jpy('input#prodOriginPrice').attr("value"))
    if org_price:
        result['originPrice'] = org_price
    else:
        result['originPrice'] = parse_number(price_box('dt:contains(价格指数) + dd').text(), 0)
    result['unit'] = jpy('input#materialUnitName').attr('value').strip()
    result['supplierId'] = jpy('input#storeId').attr('value').strip()
    result['supplierName'] = supplier.attr('title').strip()
    ext_links = list()
    if external_price_links:
        for link in external_price_links.items():
            ext_links.append(link.attr('href'))
    result['extLinks'] = ext_links

    # 价格指数
    result['priceIndex'] = parse_number(price_box('dt:contains(价格指数) + dd').text(), 0)
    # 外部均价
    result['outAvgPrice'] = parse_number(price_box('dt:contains(外部均价) + dd').text(), 0)
    # 库存
    result['stock'] = parse_number(jpy('strong.isHaveStock').attr('val'), -999)
    result['genTime'] = datetime.utcnow()
    # -------------------------------------------------

    return result


# 解析order列表页数
def parse_prod_detail(response):
    meta = response.meta
    result = meta.get('data')
    jpy = PyQuery(response.text)
    brand_li = jpy('ul.detail_list li:contains(品牌：)')
    if brand_li and brand_li.attr('title'):
        brand = brand_li.attr('title').strip()
        result['brandId'] = md5(brand)
        result['brandName'] = brand
    brand_model = jpy('ul.detail_list li span:contains(规格型号：) + span')
    if brand_model:
        result['brandModel'] = brand_model.attr('title')
    put_on_li = jpy('ul.detail_list li:contains(上架时间：)')
    if put_on_li:
        put_on_time = put_on_li.text().replace('上架时间：', '').strip()
        result['onSaleTime'] = parse_time(put_on_time)

    return result


# 解析同款商品
def parse_group(response):
    meta = response.meta
    sku_id = meta.get('skuId')
    group = ItemGroup()
    group_list = list()
    compare_list = list()
    done_set = set()
    done_set.add(sku_id)

    js = json.loads(response.text)
    if js and 'compareProd' in js:
        same_list = js.get('compareProd')
        if same_list and len(same_list):
            for same in same_list:
                same_sku_id = same.get('PROD_ID')
                # 同款商品编号
                group_list.append(same_sku_id)
                done_set.add(same_sku_id)
                # 同款商品
                compare = EsgccCompareGroup()
                compare['skuId'] = same.get('PROD_ID')
                compare['totalSaleNum'] = same.get('saleNum')
                compare['deviation'] = get_deviation(same)
                compare['gear'] = same.get('gear')
                compare_list.append(compare)

    # 本商品
    if js and 'deviation' in js:
        group_list.append(sku_id)
        compare = EsgccCompareGroup()
        compare['skuId'] = sku_id
        compare['deviation'] = get_deviation(js)
        compare['gear'] = js.get('gear')
        compare_list.append(compare)
    # 同款（含自身）
    if group_list and len(group_list):
        group['skuId'] = meta.get('skuId')
        group['spuId'] = short_uuid()
        group['skuIdList'] = group_list

    return group, compare_list, done_set


# 解析order列表页数
def parse_total_page(response):
    jpy = PyQuery(response.text)

    return int(jpy('div.page_wrap a.nextPag').prev().text().strip())


# 解析order列表
def parse_order(response):
    jpy = PyQuery(response.text)

    pages = list()
    trs = jpy('table.info_open_table tbody tr')
    if trs and trs.size():
        for tr in trs.items():
            tds = tr('td')
            if tds and tds.size():
                order_time = parse_time(tds.eq(1).text()[0:8] + '180000', fmt='%Y%m%d%H%M%S')
                order_dept = tds.eq(4).text()
                supplier_name = tds.eq(6).text()
                page = dict()
                page['id'] = tds.eq(1).text()
                page['url'] = 'http://buser.esgcc.com.cn/order/recent_purchase_detail?orderId={}'.format(
                    tds.eq(1).text())
                page['orderTime'] = order_time
                page['supplierName'] = supplier_name
                page['orderDept'] = order_dept
                page['orderUser'] = tds.eq(3).text().strip()
                page['batchNo'] = time_to_batch_no(order_time)
                page['genTime'] = datetime.utcnow()
                pages.append(page)

    return pages


# 解析sku列表
def parse_order_item(response):
    jpy = PyQuery(response.text)

    meta = response.meta
    order_time = meta.get('orderTime')
    user_id = meta.get('orderUser')
    order_id = meta.get('orderId')
    supplier_name = meta.get('supplierName')
    order_dept = meta.get('orderDept')

    orders = list()
    ul_list = jpy('div.goods_warp div.goods_info ul')
    if order_dept and len(ul_list):
        for idx, ul in enumerate(ul_list.items()):
            lis = ul('li')
            sku_url = lis.eq(1)('a').eq(0).attr('href').strip()
            order = OrderItem()
            order['id'] = order_id + '_' + str(idx)
            order['orderId'] = order_id
            order['skuId'] = str(match_sku_id(sku_url))
            # 此平台中数量可能存在小数，四舍五入兼容处理
            order['count'] = round(parse_number(lis.eq(3).text().strip()))
            order['amount'] = parse_number(lis.eq(2).text().strip())
            order['orderUser'] = user_id
            order['orderDept'] = order_dept
            order['supplierName'] = supplier_name
            order['orderTime'] = order_time
            order['batchNo'] = time_to_batch_no(order_time)
            order['genTime'] = datetime.utcnow()
            orders.append(order)
    else:
        logger.info('异常订单[%s]', order_id)

    return orders
